from django.shortcuts import render,HttpResponse
from django.views.decorators.csrf import csrf_exempt,csrf_protect


import json


def detail(request):


    net = ['10.55.1.1','10.55.1.2','10.55.3']

    return HttpResponse(json.dumps((net)))



from django.views import View

class DetailView(View):


    def get(self,request,*args,**kwargs):
        return HttpResponse('GET')

    def post(self,request,*args,**kwargs):
        return HttpResponse('POST')

    def put(self,request,*args,**kwargs):
        return HttpResponse('PUT')

    def delete(self,request,*args,**kwargs):
        return HttpResponse('DELETE')




def add(request):
    HttpResponse("添加用户")

def edit(request):
    HttpResponse("编辑用户")




class DetailView(View):
    def get(self,request,*args,**kwargs):
        ret = {
            'code':1000,
            'msg':'xxxx'
        }
        return HttpResponse(json.dumps((ret)),status=201)

    def post(self,request,*args,**kwargs):
        return HttpResponse('新增设备')

    def put(self,request,*args,**kwargs):
        return HttpResponse('更新设备')

    def delete(self,request,*args,**kwargs):
        return HttpResponse('删除设备')




# 通过Rest Framework 框架
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import exceptions



class MyAuthentication(object):
    def authenticate(self,request):
        # 获取token,也可以获取用户名和密码，去数据库中校验
        token = request._request.GET.get('token')
        if not token:
            raise exceptions.AuthenticationFailed("用户认证失败")
        return ('alex',None)

    def authenticate_header(self,val):
        pass

class UserView(APIView):
    authentication_classes = [MyAuthentication,]

    def dispatch(self, request, *args, **kwargs):
        """
        请求到来之后，都要执行dispatch方法，dispatch方法根据请求方式不同触发 get/post/put等方法

        注意：APIView中的dispatch方法有好多好多的功能
        """
        return super().dispatch(request, *args, **kwargs)

    def get(self,request,*args,**kwargs):
        ret = {
            'code':1000,
            'msg':'xxxx'
        }
        return HttpResponse(json.dumps((ret)),status=201)

    def post(self,request,*args,**kwargs):
        return HttpResponse('新增用户')

    def put(self,request,*args,**kwargs):
        return HttpResponse('更新用户')

    def delete(self,request,*args,**kwargs):
        return HttpResponse('删除用户')